<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="Spring Cloud进阶篇之Eureka原理分析, 三十五了你还啥也不是">
    <meta name="description" content="#Spring Cloud进阶篇之Eureka原理分析 
前言
之前写了几篇Spring Cloud的小白教程，相信看过的朋友对Spring Cloud中的一些应用有了简单的了解，写小白篇的目的就是为初学者建立一个基本概念，让初学者在学习的">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="referrer" content="no-referrer-when-downgrade">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>Spring Cloud进阶篇之Eureka原理分析 | 三十五了你还啥也不是</title>
    <link rel="icon" type="image/png" href="/favicon.png">
    


    <!-- bg-cover style     -->



<link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.min.css">
<link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
<link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
<link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
<link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
<link rel="stylesheet" type="text/css" href="/css/matery.css">
<link rel="stylesheet" type="text/css" href="/css/my.css">
<link rel="stylesheet" type="text/css" href="/css/dark.css" media="none" onload="if(media!='all')media='all'">




    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
    <link rel="stylesheet" href="/css/post.css">




    
        <link rel="stylesheet" type="text/css" href="/css/reward.css">
    



    <script src="/libs/jquery/jquery-3.6.0.min.js"></script>

<meta name="generator" content="Hexo 6.3.0"></head>


<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">三十五了你还啥也不是</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
  <li>
    <a href="javascript:;" class="waves-effect waves-light" onclick="switchNightMode()" title="深色/浅色模式" >
      <i id="sum-moon-icon" class="fas fa-sun" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">三十五了你还啥也不是</div>
        <div class="logo-desc">
            
            Never really desperate, only the lost of the soul.
            
        </div>
    </div>

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/blinkfox/hexo-theme-matery" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/blinkfox/hexo-theme-matery" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/3.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">Spring Cloud进阶篇之Eureka原理分析</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                          <div class="article-tag">
                            <span class="chip bg-color">无标签</span>
                          </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2023-10-08
                </div>
                

                

                

                

                
            </div>
        </div>
        <hr class="clearfix">

        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <p>#Spring Cloud进阶篇之Eureka原理分析 </p>
<h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><blockquote>
<p>之前写了几篇Spring Cloud的小白教程，相信看过的朋友对Spring Cloud中的一些应用有了简单的了解，写小白篇的目的就是为初学者建立一个基本概念，让初学者在学习的道路上建立一定的基础。</p>
<p>从今天开始，我会持续更新几篇Spring Cloud的进阶教程。</p>
</blockquote>
<h2 id="Eureka简介"><a href="#Eureka简介" class="headerlink" title="Eureka简介"></a>Eureka简介</h2><p>Eureka是Netflix开发的服务发现框架，本身就是一个基于REST的服务。Spring Cloud将它集成在其子项目spring-cloud-netflix中，用来实现服务的注册与发现功能。</p>
<p>###Eureka总体架构图</p>
<hr>
<p><img src="https://tva1.sinaimg.cn/large/006tNbRwly1g9v3ryomlwj31m20nk7a5.jpg" alt="image-20191213144413872"></p>
<p>###Eureka组件介绍</p>
<ul>
<li><p>服务注册中心集群</p>
<blockquote>
<p>分别部署在IDC1、IDC2、IDC3中心</p>
</blockquote>
</li>
<li><p>服务提供者</p>
<blockquote>
<p>服务提供者一个部署在IDC1，一个部署在IDC3</p>
</blockquote>
</li>
<li><p>服务消费者</p>
<blockquote>
<p>服务消费者一个部署在IDC1，一个部署在IDC2</p>
</blockquote>
</li>
</ul>
<p>###组件之间的调用关系</p>
<blockquote>
<p>服务提供者</p>
<ul>
<li><strong>启动服务</strong>：服务提供者会向服务注册中心发起Register请求，注册服务。</li>
<li><strong>运行过程中</strong>：服务提供者会定时向注册中心发送Renew心跳，告诉它“我还活着”。</li>
<li><strong>停止服务提供</strong>：服务提供者会向服务注册中心发送Cancel请求，告诉它清空当前服务注册信息。</li>
</ul>
<p>服务消费者</p>
<ul>
<li><strong>启动后</strong>：从服务注册中心拉取服务注册信息。</li>
<li><strong>运行过程中</strong>：定时更新服务注册信息。</li>
<li><strong>发起远程调用</strong>：</li>
<li><ul>
<li>服务消费者会从服务注册中心选择同机房的服务提供者，然后发起远程调用，只有同机房的服务提供者宕机才会去选择其他机房的服务提供者。</li>
<li>如果服务消费者发现同机房没有服务提供者，则会按照负载均衡算法选择其他机房的服务提供者，然后发起远程调用。</li>
</ul>
</li>
</ul>
<p>注册中心</p>
<ul>
<li>启动后：从其他节点拉取服务注册信息</li>
<li>运行过程中：</li>
<li><ul>
<li>定时运行Evict任务，定时清理没有按时发送Renew的服务提供者，这里的清理会将非常正常停止、网络异常等其他因素引起的所有服务。</li>
<li>接收到的Register、Renew、Cancel请求，都会同步到其他的注册中心节点。</li>
</ul>
</li>
</ul>
</blockquote>
<p><em>Eureka Server会通过Register、Renew、Get Registry等接口提供服务的注册、发现和心跳检测等。</em></p>
<p><em>Eureka Client是一个java客户端，用于简化与Eureka Server的交互，客户端本身也内置了负载均衡器（默认使用round-robin方式），在启动后会向Eureka Server发送心跳检测，默认周期为30s，Eureka Server如果在多个心跳周期内没有接收到Eureka client的某一个节点的心跳请求，Eureka Server会从服务注册中心清理到对应的Eureka Client的服务节点（默认90s）。</em></p>
<h3 id="数据结构"><a href="#数据结构" class="headerlink" title="数据结构"></a>数据结构</h3><p>服务存储的数据结构可以简单的理解为是一个两层的HashMap结构（为了保证线程安全使用的ConcurrentHashMap），具体的我们可以查看源码中的<em>AbstractInstanceRegistry</em>类：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> ConcurrentHashMap&lt;String, Map&lt;String, Lease&lt;InstanceInfo&gt;&gt;&gt; registry = <span class="keyword">new</span> <span class="title class_">ConcurrentHashMap</span>&lt;String, Map&lt;String, Lease&lt;InstanceInfo&gt;&gt;&gt;();</span><br></pre></td></tr></table></figure>

<p>第一层ConcurrentHashMap的key&#x3D;spring.application.name，也就是应用名称，value为ConcurrentHashMap。</p>
<p>第二层ConcurrentHashMap的key&#x3D;instanceId，也就是服务的唯一实例id，value为Lease对象，也就是具体的服务。Lease其实就是对InstanceInfo的包装，里面保存了实例信息、服务注册的时间等。具体的我们可以查看<em>InstanceInfo</em>源码。</p>
<h3 id="数据存储过程"><a href="#数据存储过程" class="headerlink" title="数据存储过程"></a>数据存储过程</h3><p>Eureka是通过REST接口对外提供服务的。</p>
<p>这里我以注册为例（<em>ApplicationResource</em>），首先将PeerAwareInstanceRegistry的实例注入到ApplicationResource的成员变量的registry里。</p>
<ul>
<li>ApplicationResource接收到请求后，对调用registry.register()方法。</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@POST</span></span><br><span class="line">    <span class="meta">@Consumes(&#123;&quot;application/json&quot;, &quot;application/xml&quot;&#125;)</span></span><br><span class="line">    <span class="keyword">public</span> Response <span class="title function_">addInstance</span><span class="params">(InstanceInfo info,</span></span><br><span class="line"><span class="params">                                <span class="meta">@HeaderParam(PeerEurekaNode.HEADER_REPLICATION)</span> String isReplication)</span> &#123;</span><br><span class="line">        logger.debug(<span class="string">&quot;Registering instance &#123;&#125; (replication=&#123;&#125;)&quot;</span>, info.getId(), isReplication);</span><br><span class="line">        <span class="comment">// validate that the instanceinfo contains all the necessary required fields</span></span><br><span class="line">        <span class="keyword">if</span> (isBlank(info.getId())) &#123;</span><br><span class="line">            <span class="keyword">return</span> Response.status(<span class="number">400</span>).entity(<span class="string">&quot;Missing instanceId&quot;</span>).build();</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (isBlank(info.getHostName())) &#123;</span><br><span class="line">            <span class="keyword">return</span> Response.status(<span class="number">400</span>).entity(<span class="string">&quot;Missing hostname&quot;</span>).build();</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (isBlank(info.getIPAddr())) &#123;</span><br><span class="line">            <span class="keyword">return</span> Response.status(<span class="number">400</span>).entity(<span class="string">&quot;Missing ip address&quot;</span>).build();</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (isBlank(info.getAppName())) &#123;</span><br><span class="line">            <span class="keyword">return</span> Response.status(<span class="number">400</span>).entity(<span class="string">&quot;Missing appName&quot;</span>).build();</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (!appName.equals(info.getAppName())) &#123;</span><br><span class="line">            <span class="keyword">return</span> Response.status(<span class="number">400</span>).entity(<span class="string">&quot;Mismatched appName, expecting &quot;</span> + appName + <span class="string">&quot; but was &quot;</span> + info.getAppName()).build();</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (info.getDataCenterInfo() == <span class="literal">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> Response.status(<span class="number">400</span>).entity(<span class="string">&quot;Missing dataCenterInfo&quot;</span>).build();</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (info.getDataCenterInfo().getName() == <span class="literal">null</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> Response.status(<span class="number">400</span>).entity(<span class="string">&quot;Missing dataCenterInfo Name&quot;</span>).build();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// handle cases where clients may be registering with bad DataCenterInfo with missing data</span></span><br><span class="line">        <span class="type">DataCenterInfo</span> <span class="variable">dataCenterInfo</span> <span class="operator">=</span> info.getDataCenterInfo();</span><br><span class="line">        <span class="keyword">if</span> (dataCenterInfo <span class="keyword">instanceof</span> UniqueIdentifier) &#123;</span><br><span class="line">            <span class="type">String</span> <span class="variable">dataCenterInfoId</span> <span class="operator">=</span> ((UniqueIdentifier) dataCenterInfo).getId();</span><br><span class="line">            <span class="keyword">if</span> (isBlank(dataCenterInfoId)) &#123;</span><br><span class="line">                <span class="type">boolean</span> <span class="variable">experimental</span> <span class="operator">=</span> <span class="string">&quot;true&quot;</span>.equalsIgnoreCase(serverConfig.getExperimental(<span class="string">&quot;registration.validation.dataCenterInfoId&quot;</span>));</span><br><span class="line">                <span class="keyword">if</span> (experimental) &#123;</span><br><span class="line">                    <span class="type">String</span> <span class="variable">entity</span> <span class="operator">=</span> <span class="string">&quot;DataCenterInfo of type &quot;</span> + dataCenterInfo.getClass() + <span class="string">&quot; must contain a valid id&quot;</span>;</span><br><span class="line">                    <span class="keyword">return</span> Response.status(<span class="number">400</span>).entity(entity).build();</span><br><span class="line">                &#125; <span class="keyword">else</span> <span class="keyword">if</span> (dataCenterInfo <span class="keyword">instanceof</span> AmazonInfo) &#123;</span><br><span class="line">                    <span class="type">AmazonInfo</span> <span class="variable">amazonInfo</span> <span class="operator">=</span> (AmazonInfo) dataCenterInfo;</span><br><span class="line">                    <span class="type">String</span> <span class="variable">effectiveId</span> <span class="operator">=</span> amazonInfo.get(AmazonInfo.MetaDataKey.instanceId);</span><br><span class="line">                    <span class="keyword">if</span> (effectiveId == <span class="literal">null</span>) &#123;</span><br><span class="line">                        amazonInfo.getMetadata().put(AmazonInfo.MetaDataKey.instanceId.getName(), info.getId());</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                    logger.warn(<span class="string">&quot;Registering DataCenterInfo of type &#123;&#125; without an appropriate id&quot;</span>, dataCenterInfo.getClass());</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        registry.register(info, <span class="string">&quot;true&quot;</span>.equals(isReplication));</span><br><span class="line">        <span class="keyword">return</span> Response.status(<span class="number">204</span>).build();  <span class="comment">// 204 to be backwards compatible</span></span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>AbstractInstanceRegistry在register方法里完成对服务信息的存储。</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">register</span><span class="params">(InstanceInfo registrant, <span class="type">int</span> leaseDuration, <span class="type">boolean</span> isReplication)</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            read.lock();</span><br><span class="line">            Map&lt;String, Lease&lt;InstanceInfo&gt;&gt; gMap = registry.get(registrant.getAppName());</span><br><span class="line">            REGISTER.increment(isReplication);</span><br><span class="line">            <span class="keyword">if</span> (gMap == <span class="literal">null</span>) &#123;</span><br><span class="line">                <span class="keyword">final</span> ConcurrentHashMap&lt;String, Lease&lt;InstanceInfo&gt;&gt; gNewMap = <span class="keyword">new</span> <span class="title class_">ConcurrentHashMap</span>&lt;String, Lease&lt;InstanceInfo&gt;&gt;();</span><br><span class="line">                gMap = registry.putIfAbsent(registrant.getAppName(), gNewMap);</span><br><span class="line">                <span class="keyword">if</span> (gMap == <span class="literal">null</span>) &#123;</span><br><span class="line">                    gMap = gNewMap;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            Lease&lt;InstanceInfo&gt; existingLease = gMap.get(registrant.getId());</span><br><span class="line">            <span class="comment">// Retain the last dirty timestamp without overwriting it, if there is already a lease</span></span><br><span class="line">            <span class="keyword">if</span> (existingLease != <span class="literal">null</span> &amp;&amp; (existingLease.getHolder() != <span class="literal">null</span>)) &#123;</span><br><span class="line">                <span class="type">Long</span> <span class="variable">existingLastDirtyTimestamp</span> <span class="operator">=</span> existingLease.getHolder().getLastDirtyTimestamp();</span><br><span class="line">                <span class="type">Long</span> <span class="variable">registrationLastDirtyTimestamp</span> <span class="operator">=</span> registrant.getLastDirtyTimestamp();</span><br><span class="line">                logger.debug(<span class="string">&quot;Existing lease found (existing=&#123;&#125;, provided=&#123;&#125;&quot;</span>, existingLastDirtyTimestamp, registrationLastDirtyTimestamp);</span><br><span class="line"></span><br><span class="line">                <span class="comment">// this is a &gt; instead of a &gt;= because if the timestamps are equal, we still take the remote transmitted</span></span><br><span class="line">                <span class="comment">// InstanceInfo instead of the server local copy.</span></span><br><span class="line">                <span class="keyword">if</span> (existingLastDirtyTimestamp &gt; registrationLastDirtyTimestamp) &#123;</span><br><span class="line">                    logger.warn(<span class="string">&quot;There is an existing lease and the existing lease&#x27;s dirty timestamp &#123;&#125; is greater&quot;</span> +</span><br><span class="line">                            <span class="string">&quot; than the one that is being registered &#123;&#125;&quot;</span>, existingLastDirtyTimestamp, registrationLastDirtyTimestamp);</span><br><span class="line">                    logger.warn(<span class="string">&quot;Using the existing instanceInfo instead of the new instanceInfo as the registrant&quot;</span>);</span><br><span class="line">                    registrant = existingLease.getHolder();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="comment">// The lease does not exist and hence it is a new registration</span></span><br><span class="line">                <span class="keyword">synchronized</span> (lock) &#123;</span><br><span class="line">                    <span class="keyword">if</span> (<span class="built_in">this</span>.expectedNumberOfClientsSendingRenews &gt; <span class="number">0</span>) &#123;</span><br><span class="line">                        <span class="comment">// Since the client wants to register it, increase the number of clients sending renews</span></span><br><span class="line">                        <span class="built_in">this</span>.expectedNumberOfClientsSendingRenews = <span class="built_in">this</span>.expectedNumberOfClientsSendingRenews + <span class="number">1</span>;</span><br><span class="line">                        updateRenewsPerMinThreshold();</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">                logger.debug(<span class="string">&quot;No previous lease information found; it is new registration&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            Lease&lt;InstanceInfo&gt; lease = <span class="keyword">new</span> <span class="title class_">Lease</span>&lt;InstanceInfo&gt;(registrant, leaseDuration);</span><br><span class="line">            <span class="keyword">if</span> (existingLease != <span class="literal">null</span>) &#123;</span><br><span class="line">                lease.setServiceUpTimestamp(existingLease.getServiceUpTimestamp());</span><br><span class="line">            &#125;</span><br><span class="line">            gMap.put(registrant.getId(), lease);</span><br><span class="line">            <span class="keyword">synchronized</span> (recentRegisteredQueue) &#123;</span><br><span class="line">                recentRegisteredQueue.add(<span class="keyword">new</span> <span class="title class_">Pair</span>&lt;Long, String&gt;(</span><br><span class="line">                        System.currentTimeMillis(),</span><br><span class="line">                        registrant.getAppName() + <span class="string">&quot;(&quot;</span> + registrant.getId() + <span class="string">&quot;)&quot;</span>));</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// This is where the initial state transfer of overridden status happens</span></span><br><span class="line">            <span class="keyword">if</span> (!InstanceStatus.UNKNOWN.equals(registrant.getOverriddenStatus())) &#123;</span><br><span class="line">                logger.debug(<span class="string">&quot;Found overridden status &#123;&#125; for instance &#123;&#125;. Checking to see if needs to be add to the &quot;</span></span><br><span class="line">                                + <span class="string">&quot;overrides&quot;</span>, registrant.getOverriddenStatus(), registrant.getId());</span><br><span class="line">                <span class="keyword">if</span> (!overriddenInstanceStatusMap.containsKey(registrant.getId())) &#123;</span><br><span class="line">                    logger.info(<span class="string">&quot;Not found overridden id &#123;&#125; and hence adding it&quot;</span>, registrant.getId());</span><br><span class="line">                    overriddenInstanceStatusMap.put(registrant.getId(), registrant.getOverriddenStatus());</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="type">InstanceStatus</span> <span class="variable">overriddenStatusFromMap</span> <span class="operator">=</span> overriddenInstanceStatusMap.get(registrant.getId());</span><br><span class="line">            <span class="keyword">if</span> (overriddenStatusFromMap != <span class="literal">null</span>) &#123;</span><br><span class="line">                logger.info(<span class="string">&quot;Storing overridden status &#123;&#125; from map&quot;</span>, overriddenStatusFromMap);</span><br><span class="line">                registrant.setOverriddenStatus(overriddenStatusFromMap);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="comment">// Set the status based on the overridden status rules</span></span><br><span class="line">            <span class="type">InstanceStatus</span> <span class="variable">overriddenInstanceStatus</span> <span class="operator">=</span> getOverriddenInstanceStatus(registrant, existingLease, isReplication);</span><br><span class="line">            registrant.setStatusWithoutDirty(overriddenInstanceStatus);</span><br><span class="line"></span><br><span class="line">            <span class="comment">// If the lease is registered with UP status, set lease service up timestamp</span></span><br><span class="line">            <span class="keyword">if</span> (InstanceStatus.UP.equals(registrant.getStatus())) &#123;</span><br><span class="line">                lease.serviceUp();</span><br><span class="line">            &#125;</span><br><span class="line">            registrant.setActionType(ActionType.ADDED);</span><br><span class="line">            recentlyChangedQueue.add(<span class="keyword">new</span> <span class="title class_">RecentlyChangedItem</span>(lease));</span><br><span class="line">            registrant.setLastUpdatedTimestamp();</span><br><span class="line">            invalidateCache(registrant.getAppName(), registrant.getVIPAddress(), registrant.getSecureVipAddress());</span><br><span class="line">            logger.info(<span class="string">&quot;Registered instance &#123;&#125;/&#123;&#125; with status &#123;&#125; (replication=&#123;&#125;)&quot;</span>,</span><br><span class="line">                    registrant.getAppName(), registrant.getId(), registrant.getStatus(), isReplication);</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            read.unlock();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>从源码中不难看出存储的数据结构是双层的HashMap。</p>
<p>Eureka还实现了二级缓存来保证即将对外传输的服务信息，</p>
<ul>
<li><p>一级缓存：本质还是HashMap，没有过期时间，保存服务信息的对外输出的数据结构。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> ConcurrentMap&lt;Key, Value&gt; readOnlyCacheMap = <span class="keyword">new</span> <span class="title class_">ConcurrentHashMap</span>&lt;Key, Value&gt;();</span><br></pre></td></tr></table></figure>
</li>
<li><p>二级缓存：是guava的缓存，包含失效机制，保存服务信息的对外输出的数据结构。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> LoadingCache&lt;Key, Value&gt; readWriteCacheMap;</span><br></pre></td></tr></table></figure>
</li>
<li><p>缓存的更新：</p>
</li>
</ul>
<blockquote>
<ul>
<li><p>删除二级缓存：</p>
</li>
<li><ul>
<li>client端发送register、renew、cancel请求并更新register注册表之后会删除二级缓存；</li>
</ul>
</li>
<li><p>server端自身的Evict任务剔除服务后会删除二级缓存；</p>
</li>
<li><p>二级缓存本事设置的失效机制（指的是guava实现的readWriteCacheMap），</p>
</li>
<li><p>加载二级缓存：</p>
</li>
<li><ul>
<li>client发送Get registry请求后，如果二级缓存中没有，就会触发guava的load机制，从registry中获取原始的服务信息后进行加工处理，然后放入二级缓存中；</li>
</ul>
</li>
<li><p>server端更新一级缓存的时候，如果二级缓存没有数据也会触发guava的load机制；</p>
</li>
<li><p>更新一级缓存：</p>
</li>
<li><ul>
<li>server端内置了一个time task会定时将二级缓存中的数据同步到一级缓存中，这其中包括了删除和更新。</li>
</ul>
</li>
</ul>
<p><em><strong>缓存的机制可以查看ResponseCacheImpl源码。</strong></em></p>
</blockquote>
<p>Eureka的数据结构简单总结为：</p>
<p><img src="https://tva1.sinaimg.cn/large/006tNbRwgy1g9v8d9qjx7j308k0h4dgp.jpg" alt="image-20191213173734198"></p>
<h3 id="服务注册机制"><a href="#服务注册机制" class="headerlink" title="服务注册机制"></a>服务注册机制</h3><p>服务注册中心、服务提供者、服务消费者在启动后都会向服务注册中心发起注册服务的请求（前提是配置了注册服务）。</p>
<blockquote>
<p>注册中心接到register请求后：</p>
<ul>
<li><p>将服务信息保存到registry中；</p>
</li>
<li><p>更新队列，将该事件添加到更新队列中，给Eureka client增量同步服务信息使用；</p>
</li>
<li><p>清空二级缓存，用于保证数据的一致性；（即清空的是的：<em>readWriteCacheMap</em>）</p>
</li>
<li><p>更新阈值；</p>
</li>
<li><p>同步服务信息；</p>
</li>
</ul>
</blockquote>
<h4 id="服务续约"><a href="#服务续约" class="headerlink" title="服务续约"></a>服务续约</h4><p>服务注册后，要定时发送续约请求（心跳检查），证明我还活着，不要清空我的服务信息，定时时间默认30s，可以通过配置：<strong>eureka.instance.lease-renewal-interval-in-seconds</strong>来修改。</p>
<p>注册中心接收到续约请求后（<strong>renew</strong>）：</p>
<ul>
<li>更新服务对象的最近续约时间（<strong>lastUpdateTimestamp</strong>）；</li>
<li>将信息同步给其他的节点；</li>
</ul>
<h4 id="服务注销"><a href="#服务注销" class="headerlink" title="服务注销"></a>服务注销</h4><p>正常的服务停止之前会发送注销服务请求，通知注册中心我要下线了。</p>
<p>注册中心接收到注销请求后（<strong>cancel</strong>）：</p>
<ul>
<li>将服务信息从registry中删除；</li>
<li>更新队列；</li>
<li>清空二级缓存；</li>
<li>更新阈值；</li>
<li>同步信息给其他节点；</li>
</ul>
<blockquote>
<p>说明：只有服务正常停止才会发送cancel请求，非正常停止的会通过Eureka Server的主动剔除机制进行删除。</p>
</blockquote>
<h4 id="服务剔除"><a href="#服务剔除" class="headerlink" title="服务剔除"></a>服务剔除</h4><p>服务剔除其实是一个兜底的方案，目的就是解决非正常情况下的服务宕机或其他因素导致不能发送cancel请求的服务信息清理的策略。</p>
<p>服务剔除分为：</p>
<ul>
<li>判断剔除条件</li>
<li>找出过期服务</li>
<li>清理过期服务</li>
</ul>
<blockquote>
<p>剔除条件：</p>
<ul>
<li>关闭自我保护</li>
<li>自我保护如果开启，会先判断是server还是client出现问题，如果是client的问题就会进行删除；</li>
</ul>
</blockquote>
<blockquote>
<p>自我保护机制：Eureka的自我保护机制是为了防止误杀服务提供的一种保护机制。Eureka的自我保护机制认为如果有大量的服务都续约失败，则认为自己出现了问题（例如：自己断网了），也就不剔除了。反之，则是它人的问题，就进行剔除。</p>
<p>自我保护的阈值分为server和client，如果超出阈值就是表示大量服务可用，部分服务不可用，这判定为client端出现问题。如果未超出阈值就是表示大量服务不可用，则判定是自己出现了问题。</p>
<p>阈值的计算：</p>
<ul>
<li>自我保护阈值 &#x3D; 服务总数 * 每分钟续约数 * 自我保护阈值因子；</li>
<li>每分钟续约数 &#x3D; （60s &#x2F; 客户端续约时间）；</li>
</ul>
</blockquote>
<blockquote>
<p>过期服务：</p>
<p>找出过期服务会遍历所有的服务，判断上次续约时间距离当前时间大于阈值就标记为过期，同时会将这些过期的服务保存的过期的服务集合中。</p>
</blockquote>
<blockquote>
<p>剔除服务：</p>
<p>剔除服务之前会先计算要是剔除的服务数量，然后遍历过期服务，通过洗牌算法确保每次都公平的选择出要剔除的服务，然后进行剔除。</p>
<p>执行剔除服务后：</p>
<ul>
<li>从register中删除服务信息；</li>
<li>更新队列；</li>
<li>清空二级缓存，保证数据的一致性；</li>
</ul>
</blockquote>
<h4 id="服务获取"><a href="#服务获取" class="headerlink" title="服务获取"></a>服务获取</h4><p>Eureka Client服务的获取都是从缓存中获取，如果缓存中没有，就加载数据到缓存中，然后在从缓存中取。服务的获取方式分为全量同步和增量同步两种。</p>
<blockquote>
<p>registry中只保存数据结构，缓存中存ready的服务信息</p>
</blockquote>
<ul>
<li>先读取一级缓存<ul>
<li>先判断是否开启一级缓存</li>
<li>如果开启一级缓存，就从一级缓存中取，如果一级缓存中没有，则从二级缓存中取；</li>
<li>如果没有开启一级缓存，则直接从二级缓存中取；</li>
</ul>
</li>
<li>再读取二级缓存<ul>
<li>如果二级缓存中存在，则直接返回；</li>
<li>如果二级缓存中不存在，则先将数据加载到二级缓存中，然后再读取二级缓存中的数据。</li>
</ul>
</li>
</ul>
<blockquote>
<p>注意：加载二级缓存的时候需要判断是全量还是增量，如果是增量的话，就从<em>recentlyChangedQueue</em>中加载，如果是全量的话就从<em>registry</em>中加载。</p>
</blockquote>
<h4 id="服务同步"><a href="#服务同步" class="headerlink" title="服务同步"></a>服务同步</h4><p>服务同步是Server节点之间的数据同步。分为启动时同步，运行时同步。</p>
<ul>
<li><p>启动同步</p>
<blockquote>
<p>启动同步时，会先遍历Applications中获取的服务信息，并将服务信息注册到registry中。可以参考<em>PeerAwareInstanceRegistryImpl</em>类中的<em>syncUp</em>方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line">&gt;<span class="keyword">public</span> <span class="type">int</span> <span class="title function_">syncUp</span><span class="params">()</span> &#123;</span><br><span class="line"> <span class="comment">// Copy entire entry from neighboring DS node</span></span><br><span class="line"> <span class="type">int</span> <span class="variable">count</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line"> <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; ((i &lt; serverConfig.getRegistrySyncRetries()) &amp;&amp; (count == <span class="number">0</span>)); i++) &#123;</span><br><span class="line">     <span class="keyword">if</span> (i &gt; <span class="number">0</span>) &#123;</span><br><span class="line">         <span class="keyword">try</span> &#123;</span><br><span class="line">             Thread.sleep(serverConfig.getRegistrySyncRetryWaitMs());</span><br><span class="line">         &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">             logger.warn(<span class="string">&quot;Interrupted during registry transfer..&quot;</span>);</span><br><span class="line">             <span class="keyword">break</span>;</span><br><span class="line">         &#125;</span><br><span class="line">     &#125;</span><br><span class="line">     <span class="type">Applications</span> <span class="variable">apps</span> <span class="operator">=</span> eurekaClient.getApplications();</span><br><span class="line">     <span class="keyword">for</span> (Application app : apps.getRegisteredApplications()) &#123;</span><br><span class="line">         <span class="keyword">for</span> (InstanceInfo instance : app.getInstances()) &#123;</span><br><span class="line">             <span class="keyword">try</span> &#123;</span><br><span class="line">                 <span class="keyword">if</span> (isRegisterable(instance)) &#123;</span><br><span class="line">                     register(instance, instance.getLeaseInfo().getDurationInSecs(), <span class="literal">true</span>);</span><br><span class="line">                     count++;</span><br><span class="line">                 &#125;</span><br><span class="line">             &#125; <span class="keyword">catch</span> (Throwable t) &#123;</span><br><span class="line">                 logger.error(<span class="string">&quot;During DS init copy&quot;</span>, t);</span><br><span class="line">             &#125;</span><br><span class="line">         &#125;</span><br><span class="line">     &#125;</span><br><span class="line"> &#125;</span><br><span class="line"> <span class="keyword">return</span> count;</span><br><span class="line">&gt;&#125;</span><br></pre></td></tr></table></figure>

<p>注意这个方法使用类两层for循环，第一次循环时保证自己已经拉取到服务信息，第二层循环是遍历拉取到服务注册信息。</p>
</blockquote>
</li>
<li><p>运行时同步</p>
<blockquote>
<p>server端当有reigster、renew、cancel请求进来时，会将这些请求封装到一个task中，然后放到一个队列当中，然后经过一系列的处理后，在放到另一个队列中。	可以查看<em>PeerAwareInstanceRegistryImpl</em>类中的<em>BatchWorkerRunnable</em>类，这里就不再贴源码了。</p>
</blockquote>
</li>
</ul>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>Eureka的原理接介绍到这里，从整体上看似简单，但实现细节相关复杂。得多看几遍源码才能猜透他们的设计思路。</p>
<p>Eureka作为服务的注册与发现，它实际的设计原则是遵循AP原则，也就是“数据的最终一致性”。现在还有好多公司使用zk、nacos来作为服务的注册中心，后续会简单更新一篇关于服务注册中心的对比，这里就不过多阐述。</p>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">MaoMao</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="http://maomaov5.gitee.io/2023/10/08/spring-cloud-jin-jie-pian-zhi-eureka-yuan-li-fen-xi/">http://maomaov5.gitee.io/2023/10/08/spring-cloud-jin-jie-pian-zhi-eureka-yuan-li-fen-xi/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">MaoMao</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            <span class="chip bg-color">无标签</span>
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力!!☕️☕️☕️</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/ali-pay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat-pay.jpg" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2023/10/08/spring-cloud-alibaba-xiao-bai-jiao-cheng-xi-lie-zhi-san-sentinel-de-da-jian-yu-shi-yong/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/23.jpg" class="responsive-img" alt="spring cloud alibaba小白教程系列之（三）Sentinel的搭建与使用">
                        
                        <span class="card-title">spring cloud alibaba小白教程系列之（三）Sentinel的搭建与使用</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2023-10-08
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-user fa-fw"></i>
                            MaoMao
                            
                        </span>
                    </div>
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                本篇&nbsp;<i class="far fa-dot-circle"></i>
            </div>
            <div class="card">
                <a href="/2023/10/08/spring-cloud-jin-jie-pian-zhi-eureka-yuan-li-fen-xi/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/3.jpg" class="responsive-img" alt="Spring Cloud进阶篇之Eureka原理分析">
                        
                        <span class="card-title">Spring Cloud进阶篇之Eureka原理分析</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2023-10-08
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-user fa-fw"></i>
                            MaoMao
                            
                        </span>
                    </div>
                </div>

                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>



<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>



    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="503838841"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="/libs/aplayer/Meting.min.js"></script>

    

    <div class="container row center-align"
         style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2019-2023</span>
            
            <a href="/about" target="_blank">MaoMao</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            
            <br>
            
            
            
                
            
            
                <span id="busuanzi_container_site_pv">
                &nbsp;|&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;
                    <span id="busuanzi_value_site_pv" class="white-color"></span>
            </span>
            
            
                <span id="busuanzi_container_site_uv">
                &nbsp;|&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;
                    <span id="busuanzi_value_site_uv" class="white-color"></span>
            </span>
            
            <br>

            <!-- 运行天数提醒. -->
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/blinkfox" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:4272231@163.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=95472323" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 95472323" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 白天和黑夜主题 -->
<div class="stars-con">
    <div id="stars"></div>
    <div id="stars2"></div>
    <div id="stars3"></div>  
</div>

<script>
    function switchNightMode() {
        $('<div class="Cuteen_DarkSky"><div class="Cuteen_DarkPlanet"></div></div>').appendTo($('body')),
        setTimeout(function () {
            $('body').hasClass('DarkMode') 
            ? ($('body').removeClass('DarkMode'), localStorage.setItem('isDark', '0'), $('#sum-moon-icon').removeClass("fa-sun").addClass('fa-moon')) 
            : ($('body').addClass('DarkMode'), localStorage.setItem('isDark', '1'), $('#sum-moon-icon').addClass("fa-sun").removeClass('fa-moon')),
            
            setTimeout(function () {
            $('.Cuteen_DarkSky').fadeOut(1e3, function () {
                $(this).remove()
            })
            }, 2e3)
        })
    }
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    

    
    
    

    <!-- 雪花特效 -->
    

    <!-- 鼠标星星特效 -->
    

     
        <script src="https://ssl.captcha.qq.com/TCaptcha.js"></script>
        <script src="/libs/others/TencentCaptcha.js"></script>
        <button id="TencentCaptcha" data-appid="xxxxxxxxxx" data-cbfn="callback" type="button" hidden></button>
    

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    <!--腾讯兔小巢-->
    
    

    

    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
